/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package generator.statements;

import generator.collections.AbstractTable;

/**
 * Abstract SQL record mapper.
 * 
 * @author Marek Snopkowski <snpy@snpy.info>
 * @version 11.04.2008
 */
abstract public class Statement
{
    protected int id;
    
    protected String tableName;
    
    /**
     * Default statement c-tor.
     * 
     * ID is be globally unique and SQL table name is the same as class name.
     * 
     */
    public Statement()
    {
        id        = AbstractTable.autoincrement();
        tableName = this.getClass().getName();
        tableName = tableName.substring(tableName.lastIndexOf('.') + 1);
    }
    
    public static int getTypesCount()
    {
        return 0;
    }
    
    /**
     * Returns table name according on instance set up.
     * 
     * @return SQL table name.
     */
//    public String getTableName()
//    {
//        return tableName;
//    }
    
    abstract public String getTableName();
    
    abstract public String getFieldsNameSet();
    
    abstract public Object[] getFieldsValueCollection();
    
    private String getFieldsValueSet()
    {
        Object[] coll = getFieldsValueCollection();
        String set = "";
        
        for (Object c : coll)
            set += ", " + nullize(c);
        
        return set.substring(2);
    }
    
    public String nullize(Object arg)
    {
        if (null == arg)
            return "NULL";
        
        
        return String.format("N'%s'", arg);
    }
    
    public int getId()
    {
        return id;
    }
    
    @Override
    public String toString()
    {
        return String.format("INSERT INTO [%s] (%s)\nVALUES (%s)\n", 
                getTableName(), getFieldsNameSet(), getFieldsValueSet());
    }
    
    public String prepareValues()
    {
        return String.format("\n  (%s),", getFieldsValueSet());
    }
}
